package com.oocl.im.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;

import com.oocl.im.handler.ChatHandler;
import com.oocl.im.handler.LoginHandler;
import com.oocl.im.pojo.MsgPackage;
import com.oocl.im.pojo.Operation;

public class LoginServer implements Runnable {
	private HashMap<String, ChatHandler> handlerPool;
	private ExecutorService threadPool;
	private ServerSocket serverSocket;

	public HashMap<String, ChatHandler> getHandlerPool() {
		return handlerPool;
	}

	public LoginServer() {
		super();
	}

	public LoginServer(ExecutorService threadPool) {
		super();
		this.threadPool = threadPool;
		this.handlerPool = new HashMap<>();
	}

	public void run() {
		try {
			serverSocket = new ServerSocket(8123);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			while (true) {

				Socket socket = serverSocket.accept();
				threadPool.submit(new LoginHandler(socket, handlerPool,
						threadPool));

			}
		} catch (IOException e) {
			System.out.println("Login server close");
		}
	}

	public void close() {
		try {
			for (Entry<String, ChatHandler> entry : handlerPool.entrySet()) {
				if (entry.getValue() != null) {
					entry.getValue().exit(
							new MsgPackage(Operation.EXIT, entry.getKey(),
									null, null, null, null));
				}
			}
			serverSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
